﻿using Dapper.Extensions;
using OF.Utility;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 公共
    /// 用户提供多个页面调用的方法
    /// </summary>
    public class CommonController : BaseApiController
    {
        private HotMobileService _service = new HotMobileService();
        private NoticeService _nSerivce = new NoticeService();
        private BannerService _bService = new BannerService();
        private WashShopService _shopService = new WashShopService();
        string FileUploadUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");


        /// <summary>
        /// 获取热门电话
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<HotMobile>> HotMobiles()
        {
            var data = _service.QueryAll().Where(t => t.IsActive == 1).ToList();
            foreach (var item in data)
            {
                item.MobileLogoUrl = string.Format("{0}/{1}", FileUploadUrl, item.MobileLogo);
            }
            return ResultData<List<HotMobile>>.Success(data);
        }

        /// <summary>
        /// 获取公告
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<Notice>> Notices(int carGroupId)
        {
            var data = _nSerivce.GetNotices(carGroupId);
            return ResultData<List<Notice>>.Success(data);
        }

        /// <summary>
        /// 获取公告详情
        /// </summary>
        /// <param name="noticeId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Notice> NoticeDetail(int noticeId)
        {
            var data = _nSerivce.SingleOrDefault(noticeId);
            if (data != null)
            {
                data.NoticeImgUrl = string.Format("{0}/{1}", FileUploadUrl, data.NoticeImgUrl);
            }
            return ResultData<Notice>.Success(data);
        }

        /// <summary>
        /// 行驶证识别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Task<ResultData<string>> FileUpload()
        {
            // 确定指定的内容是否是 MIME 多部分内容
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string imgUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");
            ResultData<string> rt = new ResultData<string>();

            //指定要将文件存入的服务器物理位置  
            string savePath = ConfigHelper.GetAppSettingValue("FileUploadPath");
            string saveListPath = ConfigHelper.GetAppSettingValue("FileUploadYSPath");
            var provider = new MultipartFormDataStreamProvider(savePath);
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }
                    //获取上传文件
                    foreach (MultipartFileData file in provider.FileData)
                    {
                        //api默认保存的文件没有后缀名,需要重命名
                        FileInfo f = new FileInfo(file.LocalFileName);
                        int idx = file.Headers.ContentDisposition.FileName.LastIndexOf('.');
                        string pfx = file.Headers.ContentDisposition.FileName.Substring(idx);

                        //api的文件名,自动添加了双引号(")，此处去掉，否则会提示非法路径。  真坑
                        string newFileName = file.LocalFileName + pfx.Replace("\"", string.Empty);
                        f.MoveTo(newFileName);

                        using (var img = Image.FromFile(newFileName))
                        {
                            //缩略图
                            PictureUtility.ComPressJPEG(img, img.Width, img.Height)
                     .Save(Path.Combine(newFileName.Replace(savePath, saveListPath)));
                        }

                        rt.data = imgUrl + f.Name;
                    }
                    return rt;
                });
            return task;
        }

        /// <summary>
        /// 根据分类获取最近三条信息 
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<Banner>> GetBannerList(int category)
        {
            var data = _bService.GetTop3List(category);
            foreach (var item in data)
            {
                item.DetailImageUrl = string.Format("{0}/{1}", FileUploadUrl, item.ImageUrl);
            }
            return ResultData<List<Banner>>.Success(data);
        }

        /// <summary>
        /// 查询洗车店
        /// </summary>
        /// <param name="districtId">区县ID</param>
        /// <param name="search">名称或地址</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="longitude">经度</param>
        /// <param name="latitude">维度</param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Page<WashShop>> GetWorkShops(int districtId, int pageIndex, int pageSize, double longitude, double latitude, string search = null)
        {
            var page = _shopService.GetWorkShops(districtId, search, pageIndex, pageSize);
            foreach (var item in page.rows)
            {
                item.Distance = 0;
                if (longitude > 0 && latitude > 0)
                {
                    item.Distance = Convert.ToInt32(Algorithm(item.Longitude, item.Latitude, longitude, latitude));
                }
                if (!string.IsNullOrWhiteSpace(item.ImageUrl))
                    item.ImageUrl = string.Format("{0}/{1}", FileUploadUrl, item.ImageUrl);
            }
            //首次加载
            if (page.rows.Count > pageSize)
            {
                page.rows = page.rows.OrderBy(x => x.Distance).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                page.rows = page.rows.OrderBy(x => x.Distance).ToList();
            }               
           
            return ResultData<Page<WashShop>>.Success(page);
        }

        /// <summary>
        /// 返回目标地点公里数
        /// </summary>
        /// <param name="longitude1">目标经度</param>
        /// <param name="latitude1">目标纬度</param>
        /// <param name="longitude2">当前位置经度</param>
        /// <param name="latitude2">当前位置纬度</param>
        /// <returns></returns>
        private double Algorithm(double longitude1, double latitude1, double longitude2, double latitude2)
        {
            double Lat1 = rad(latitude1); // 纬度
            double Lat2 = rad(latitude2);
            double a = Lat1 - Lat2;//两点纬度之差
            double b = rad(longitude1) - rad(longitude2); //经度之差
            double s = 2 * Math.Asin(Math
                          .Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(Lat1) * Math.Cos(Lat2) * Math.Pow(Math.Sin(b / 2), 2)));//计算两点距离的公式
            s = s * 6378137.0;//弧长乘地球半径（半径为米）
            s = Math.Round(s * 10000d) / 10000d;//精确距离的数值
            return s / 1000;
        }

        /// <summary>
        /// 角度转换成弧度
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private double rad(double d)
        {
            return d * Math.PI / 180.00; //角度转换成弧度
        }

       
    }
}
